<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>SSE</title>
</head>
<body>
<button type="button" onclick="output()">输出</button>
<div id="sse" style="white-space: pre-line"></div>
<script>
    function output() {
        const source = new EventSource("http://localhost:8818/sse/test1");
        console.log("source=>", source);
        source.onopen = function () {
            console.log("open");
        }
        source.onmessage = function (event) {
            console.log("event=>", event);
            const text = event.data;
            console.log("data=>", text);
            const el = document.getElementById("sse");
            el.innerText += text;
        };
        source.onerror = (event) => {
            console.log("onerror", source.readyState);
            if (source.readyState === EventSource.CONNECTING) {
                // 如果只想输出一次,就调用关闭方法关闭连接
                source.close();
                console.log('closed');

            }
        };
    }
</script>
</body>
</html>